﻿using HalconDotNet;
using MotionControl;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using WHW_NetUtility;
using XXTUserUI;

namespace MainFrame
{
    public partial class PageMain : Form
    {
        
        public PageMain()
        {
            InitializeComponent();

            //内部控件绑定到静态控件中
            control = tabPage1;
        }

        private void panel10_Paint(object sender, PaintEventArgs e)
        {

        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        string msg1 = "";
        string msg2 = "";
        string msg3 = "";
        public void MessageDisplay(string message)
        {
            try
            {
                if (msg1 != message)
                {
                    msg1 = message;
                }
                else
                {
                    return;
                }

                rbt_runlog.BeginInvoke(new MethodInvoker(() =>
                {
                    if (rbt_runlog.Lines.Length > 2000)
                    {
                        rbt_runlog.Text = "";
                    }
                    DateTime NowTime = DateTime.Now;
                    rbt_runlog.AppendText(NowTime.ToString("yyyy/MM/dd HH:mm:ss.fff") + ":" + message + Environment.NewLine);
                    rbt_runlog.ScrollToCaret();
                }));
                Log4Helper.WriteLog("界面信息", message);
            }
            catch (Exception)
            {
            }

        }
        public void MessageDisplay(string message, string english = "")
        {
            try
            {
                if (msg2 != message)
                {
                    msg2 = message;
                }
                else
                {
                    return;
                }
                rbt_runlog.BeginInvoke(new MethodInvoker(() =>
                {
                    if (rbt_runlog.Lines.Length > 3000)
                    {
                        rbt_runlog.Text = "";
                    }
                    DateTime NowTime = DateTime.Now;
                    rbt_runlog.AppendText(NowTime.ToString("yyyy/MM/dd HH:mm:ss.fff") + ":" + message + Environment.NewLine);
                    rbt_runlog.ScrollToCaret();
                }));



                Log4Helper.WriteLog("界面信息", message);
            }
            catch (Exception)
            {
            }

        }

        public void AlarmMessageDisplay(string message)
        {
            try
            {
                if (msg3 != message)
                {
                    msg3 = message;
                }
                else
                {
                    return;
                }
                string str = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.fff") + ":" + message + Environment.NewLine;
                rbt_alarmlog.BeginInvoke(new MethodInvoker(() =>
                {
                    if (rbt_alarmlog.Lines.Length > 2000)
                    {
                        rbt_alarmlog.Text = "";
                    }
                    rbt_alarmlog.SelectionColor = Color.Red;
                    rbt_alarmlog.SelectedText = str;
                    rbt_alarmlog.ScrollToCaret();

                }));
                Log4Helper.WriteLogError(message);
            }
            catch (Exception)
            {
            }

        }
        private void label20_Click(object sender, EventArgs e)
        {

        }
        bool isfirst = true;
        string path_Save = Environment.CurrentDirectory + "\\CSV";
        private List<Button> lst_Button = new List<Button>();
        private void PageMain_Load(object sender, EventArgs e)
        {
            if(isfirst)
            {
                bool Result1 = false;
                //打开视觉软件嵌入窗体
                //OpenVisionWindow(out Result1);

                displalyInfo.displayInfoMain += MessageDisplay;//关联信息提示全局变量
                displalyInfo.displayInfoMainBox += MessageDisplay;//关联信息提示全局变量
                displalyInfo.displayErrorMain = AlarmMessageDisplay;//关联信息提示全局变量
                MotionControl.GlobalVariable.MessageDisplay = MessageDisplay;//不同工程间的信息提示
                isfirst = false;
                GlobalVar.btn_Start = btn_StartProccess;
                GlobalVar.btn_Home = btn_HomeProccess;
                GlobalVar.btn_Estop = btn_EstopProccess;
                lst_Button.Add(btn_Pause);
                lst_Button.Add(btn_Start);
                lst_Button.Add(btn_Home);
                lst_Button.Add(btn_FinishWork);
                lst_Button.Add(btn_estop);
                lst_Button.Add(btn_ChangeStatus);
             
                GlobalVar.sw_CT.Stop();
                GlobalVar.displayCycleTime_Label+= displayCT_labelReal;
                GlobalVar.displayCycleTime_label_STOP += displayCT_labelReal_stop;
                displalyInfo.addInfoRow = addRowToDisplay;//关联信息提示全局变量
                Task.Factory.StartNew(Task_FormInfoDisplay);
                Task.Factory.StartNew(Task_RunTime);
                var plcList = new ContextMenuStrip();
                var zoomAdd = new ToolStripMenuItem("重置总数");
                zoomAdd.Click += new System.EventHandler(this.btn_clearData_Click);
                plcList.Items.Add(zoomAdd);

                tableLayoutPanel13.ContextMenuStrip = plcList;
           
                GlobalVar.imageDisplayResult_cur += ImageDisplay_main;
                GlobalVar.imageDisplayResult_Last += ImageDisplay_Last;
                cmb_workMode.Text = e_WorkMode.生产模式.ToString();
                lbl_cutRFID1.Focus();
            }

            

        }
        private void btn_clearData_Click(object sender, EventArgs e)
        {
            GlobalVar.closeSave.Count = 0;
            GlobalVar.closeSave.OKCount = 0;
            GlobalVar.closeSave.NGCount = 0;
        }

        //20241209增加海康视觉屏蔽
        public void ImageDisplay_main()
        {
            //try
            //{
            //    tabControl1.BeginInvoke(new Action(()=>
            //    {
            //        tabControl1.SelectedIndex = 0;
            //        hswc_curDisplay.BeginInvoke(new MethodInvoker(() =>
            //        {
            //            hswc_curDisplay.HalconWindow.ClearWindow();
            //            if (GlobalVar.curResult_Pos.sourceImage != null)//原图
            //            {
            //                GlobalVar.curResult_Pos.sourceImage.DispObj(hswc_curDisplay.HalconWindow);
            //                hswc_curDisplay.SetFullImagePart();
            //                if (GlobalVar.curResult_Pos.tempxld != null)//模板XLD
            //                {
            //                    hswc_curDisplay.HalconWindow.SetDraw("margin");
            //                    hswc_curDisplay.HalconWindow.SetColor("green");
            //                    GlobalVar.curResult_Pos.tempxld.DispObj(hswc_curDisplay.HalconWindow);
            //                }
            //                if (GlobalVar.curResult_Pos.crossing != null)//十字架
            //                {
            //                    hswc_curDisplay.HalconWindow.SetDraw("margin");
            //                    hswc_curDisplay.HalconWindow.SetColor("red");
            //                    GlobalVar.curResult_Pos.crossing.DispObj(hswc_curDisplay.HalconWindow);
            //                }
            //                if (!string.IsNullOrEmpty(GlobalVar.curResult_Pos.msg))//十字架
            //                {
            //                    if (GlobalVar.curResult_Pos.msg.Contains("NG"))
            //                        hswc_curDisplay.HalconWindow.DispText(GlobalVar.curResult_Pos.msg, "window", 50, 100, "red", "box", "false");
            //                    else
            //                        hswc_curDisplay.HalconWindow.DispText(GlobalVar.curResult_Pos.msg, "window", 50, 100, "green", "box", "false");
            //                }
            //                Task.Run(() =>
            //                {
            //                    Thread.Sleep(1000);
            //                    GlobalVar.lastResult_Pos = JsonConvert.DeserializeObject<ImageReult>(JsonConvert.SerializeObject(GlobalVar.curResult_Pos));
            //                    GlobalVar.lastResult_Pos.msg = "上一次结果:" + DateTime.Now.ToString("HH:mm:ss fff") + GlobalVar.lastResult_Pos.msg;
            //                });
            //            }
            //        }));
            //    }));
                    
            //}
            //catch (Exception ex)
            //{
            //    displalyInfo.displayInfoMain("ImageDisplay_main:" + ex.Message);
              
            //}

        }

        public void ImageDisplay_Last()
        {
            try
            {
                tabControl1.BeginInvoke(new Action(()=>
                {
                    tabControl1.SelectedIndex = 1;
                    hswc_lastDisplay.BeginInvoke(new MethodInvoker(() =>
                    {
                        hswc_lastDisplay.HalconWindow.ClearWindow();
                        if (GlobalVar.lastResult_Pos.sourceImage != null)//原图
                        {
                            GlobalVar.lastResult_Pos.sourceImage.DispObj(hswc_lastDisplay.HalconWindow);
                            hswc_lastDisplay.SetFullImagePart();
                            if (GlobalVar.lastResult_Pos.tempxld != null)//模板XLD
                            {
                                hswc_lastDisplay.HalconWindow.SetDraw("margin");
                                hswc_lastDisplay.HalconWindow.SetColor("green");
                                GlobalVar.lastResult_Pos.tempxld.DispObj(hswc_lastDisplay.HalconWindow);
                            }
                            if (GlobalVar.lastResult_Pos.crossing != null)//十字架
                            {
                                hswc_lastDisplay.HalconWindow.SetDraw("margin");
                                hswc_lastDisplay.HalconWindow.SetColor("red");
                                GlobalVar.lastResult_Pos.crossing.DispObj(hswc_lastDisplay.HalconWindow);
                            }
                            if (!string.IsNullOrEmpty(GlobalVar.lastResult_Pos.msg))//十字架
                            {
                                if (GlobalVar.lastResult_Pos.msg.Contains("NG"))
                                    hswc_lastDisplay.HalconWindow.DispText(GlobalVar.lastResult_Pos.msg, "window", 50, 100, "red", "box", "false");
                                else
                                    hswc_lastDisplay.HalconWindow.DispText(GlobalVar.lastResult_Pos.msg, "window", 50, 100, "green", "box", "false");
                            }
                        }
                    }));
                }));
                
            }
            catch (Exception ex)
            {
                displalyInfo.displayInfoMain("ImageDisplay_main:" + ex.Message);

            }

        }
        /// <summary>
        /// 运行  故障 停机 时间的计算
        /// </summary>
        private void Task_RunTime()
        {
            try
            {
                var curTime = DateTime.Now;
                var curRunTime = curTime;
                var curStopTime = curTime;
                var curEstopTime = curTime;
                while (!GlobalVar.isExit)
                {
                    Thread.Sleep(100);
                    curTime = DateTime.Now;
                    if (GlobalVar.isAutoRun&&!GlobalVar.isPause)
                    {
                        if (curRunTime < curTime.AddMilliseconds(-250))
                        {
                            curRunTime = curTime;
                        }
                        else
                        {
                            GlobalVar.closeSave.runTime_today=GlobalVar.closeSave.runTime_today.AddMilliseconds((curTime - curRunTime).TotalMilliseconds);
                            curRunTime = curTime;
                        }
                    }
                    else
                    {
                        if(GlobalVar.isEstop)
                        {
                            if (curEstopTime < curTime.AddMilliseconds(-250))
                            {
                                curEstopTime = curTime;
                            }
                            else
                            {
                                GlobalVar.closeSave.EstopTime_today= GlobalVar.closeSave.EstopTime_today.AddMilliseconds((curTime - curEstopTime).TotalMilliseconds);
                                curEstopTime = curTime;
                            }
                        }
                        else
                        {
                            if(curStopTime< curTime.AddMilliseconds(-250))
                            {
                                curStopTime = curTime;
                            }
                            else
                            {
                                GlobalVar.closeSave.stopTime_today=GlobalVar.closeSave.stopTime_today.AddMilliseconds((curTime - curStopTime).TotalMilliseconds);
                                curStopTime = curTime;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                displalyInfo.displayErrorMain(Thread.CurrentThread.Name + ex.Message);
            }
        }
        public DateTime curCTTime = DateTime.Now;
        
        public void displayCT_labelReal()
        {
            //GlobalVar. sw_CT.Restart();
            //this.BeginInvoke(new Action(() =>
            //{
            //    var str = ((DateTime.Now - curCTTime).TotalMilliseconds / (double)1000).ToString("F02");
            //    curCTTime = DateTime.Now;
            //    lbl_CT.Text = str;
            //}));
        }
        public void displayCT_labelReal_stop()
        {
            //GlobalVar.sw_CT.Stop();
            //this.BeginInvoke(new Action(() =>
            //{
            //    var str = ((DateTime.Now - curCTTime).TotalMilliseconds / (double)1000).ToString("F02");
            //    curCTTime = DateTime.Now;
            //    lbl_CT.Text = str;
            //}));
        }
        public void addRowToDisplay(ProductInfo info)
        {
            try
            {
                if (string.IsNullOrEmpty(info.ProId) || info.ProId.Contains(GlobalVar.userConfig.RFIDBox.NGflag) || info.ProId.Length <= 5||GlobalVar.IsThrought)
                {
                    displalyInfo.displayErrorMain($"产品为{JsonConvert.SerializeObject(info)}不进行信息录入与上传");
                    return;
                }
                this.Invoke(new Action(() =>
                {
                    GlobalVar.closeSave.Count++;
                    //  if (info.Result_down ==e_Result.出料OK.ToString()|| info .Result== e_Result.写入读卡器OK.ToString() || info.Result == e_Result.贴膜OK.ToString())
                    if (!info.Result_up.Contains("NG"))
                        GlobalVar.closeSave.OKCount++;
                    else
                        GlobalVar.closeSave.NGCount++;

                    var rCount = dgv_display.Rows.Count;
                    if (rCount > 0)
                        rCount = Convert.ToInt32(dgv_display.Rows[rCount - 1].Cells[0].Value.ToString());
                    if (dgv_display.Rows.Count > 500)
                        dgv_display.Rows.Clear();
                    rCount++;
                    dgv_display.Rows.Add(rCount, info.ProId,info.ProId_out,
                        info.LaserTime == null ? "" : info.LaserTime?.ToString("yyyy-MM-dd HH:mm:ss"),
                        info.LabelTime == null ? "" : info.LabelTime?.ToString("yyyy-MM-dd HH:mm:ss"),
                         info.Result,info.Result_Cut,info.Result_Label);
                    dgv_display.FirstDisplayedScrollingRowIndex = dgv_display.Rows.Count - 1;
                    if (info.Result_Cut.Contains("NG"))
                    {
                        dgv_display.Rows[(int)dgv_display.Rows.Count - 1].Cells["dgvc_Result_Cut"].Style.ForeColor = Color.Red;
                    }
                    if (info.Result_Label.Contains("NG"))
                    {
                        dgv_display.Rows[(int)dgv_display.Rows.Count - 1].Cells["dgvc_Result_Label"].Style.ForeColor = Color.Red;
                    }
                }));
                WriteCSV(info);
                var ret = GlobalVar.sqlHelper.insert<ProductInfo>(GlobalVar.userConfig.db_T_Product, info);
                if (GlobalVar.userConfig.UploadInfo.IsUploadUrl)
                {
                    if (!string.IsNullOrEmpty(GlobalVar.userConfig.UploadInfo.url_DataUpload) && GlobalVar.userConfig.RFIDBox.IsEnable)
                    {
                        Task.Run(new Action(() =>
                        {
                            UploadInterface.upload_DataUpload(info);
                        }));
                    }

                }
                displalyInfo.displayInfoMain(ret == 1 ? "插入生产数据成功" : "插入生产数据失败");
            }
            catch (Exception ex)
            {
                displalyInfo.displayErrorMain("显示数据：" + ex.Message);
            }
        }
        public void WriteCSV(ProductInfo info)
        {
            if (!Directory.Exists(path_Save))
            {
                Directory.CreateDirectory(path_Save);
            }
            string saveDate = DateTime.Now.ToString("yyyy_MM_dd");
            var filepath = path_Save + "\\" + saveDate + ".CSV";
            var str_Start = info.LaserTime == null ? "" : info?.LaserTime?.ToString("yyyy-MM-dd HH:mm:ss");
            var str_End = info.LabelTime == null ? "" : info?.LabelTime?.ToString("yyyy-MM-dd HH:mm:ss");
            var proid = info.ProId == null ? "" : info.ProId;
            var str = info.ProNo.ToString() + "," + proid + "," + str_Start + "," + str_End + "," + info.typeName + "," + info.Result_up.ToString() + ","
                + info.Result_down.ToString() + "," + info.Result.ToString() + "," + info.Result_Cut.ToString() + "," + info.Result_Label.ToString();

            if (!File.Exists(filepath))
            {
                FileStream fs = new FileStream(filepath, FileMode.OpenOrCreate);
                StreamWriter csvStreamWriter = new StreamWriter(fs, Encoding.UTF8);
                csvStreamWriter.WriteLine("平台号,工装ID,开始时间,结束时间,生产配方,上游结果,下游结果,结果,撕膜结果,贴标结果");
                csvStreamWriter.WriteLine(str);
                csvStreamWriter.Flush();
                csvStreamWriter.Close();
                fs.Close();
            }
            else
            {
                FileStream fs = new FileStream(filepath, FileMode.Append);
                StreamWriter csvStreamWriter = new StreamWriter(fs, Encoding.UTF8);
                csvStreamWriter.WriteLine(str);
                csvStreamWriter.Flush();
                csvStreamWriter.Close();
                fs.Close();
            }

        }

        private void Task_FormInfoDisplay()
        {
            try
            {
                while (!GlobalVar.isExit)
                {
                    Thread.Sleep(100);
          
                    this.Invoke(new Action(() =>
                    {
                        #region 左边
                        if (GlobalVar.isAutoRun)
                        {
                            if (GlobalVar.IsEndWork)
                            {
                                if (GlobalVar.isPause)
                                {
                                    lbl_Status.Text = "停止中";
                                    lbl_Status.BackColor = Color.Orange;
                                }
                            }
                            if (GlobalVar.isPause)
                            {
                                btn_ChangeStatus.Text = "手动中";
                                if (!GlobalVar.IsEndWork)
                                {
                                    lbl_Status.Text = "暂停中";
                                    lbl_Status.BackColor = Color.Orange;
                                }
                            }
                            else
                            {
                                GlobalVar.IsStatusAuto = true;
                               
                                lbl_Status.Text = "启动中";
                                lbl_Status.BackColor = Color.LightGreen;
                            }
                        }
                        else
                        {
                   
                            if (GlobalVar.isEstop)
                            {
                                GlobalVar.IsStatusAuto = false;
                                lbl_Status.Text = "急停中";
                                lbl_Status.BackColor = Color.Red;
                            }
                            else
                            {
                                if(GlobalVar.isReseting)
                                {
                                    lbl_Status.Text = "复位中";
                                }
                                else
                                 lbl_Status.Text = "停止中";
                                lbl_Status.BackColor = Color.Orange;
                            }
                           
                        }
                        if (!GlobalVar.isAllHome && !GlobalVar.isAutoRun && !GlobalVar.isReseting)
                        {
                            btn_Home.Enabled = true;
                        }
                        btn_FinishWork.Enabled = !GlobalVar.IsEndWork;
                        btn_FinishWork.Text = GlobalVar.IsEndWork ? "结束作业中" : "停止";
                        cmb_workMode.Enabled = !GlobalVar.isAutoRun;
                        btn_ChangeStatus.Text = GlobalVar.IsStatusAuto?"自动中": "手动中";
                    //    btn_Start.Enabled = !GlobalVar.isAutoRun;
                        btn_ChangeStatus.Enabled = !(GlobalVar.isAutoRun&& !GlobalVar.isPause);
                        btn_Start.Enabled = !(GlobalVar.isAutoRun && !GlobalVar.isPause ||GlobalVar.isReseting);
                        if (MotionControl.GlobalVariable.OperLevel != (int)MotionControl.operLevel.superAdmin)
                            btn_estop.Visible = false;
                        else
                            btn_estop.Visible = true;
                        if (GlobalVar.isEstop)
                        {
                            btn_estop.Text = "急停取消";
                        }else
                        {
                            btn_estop.Text = "急停";
                        }
                        if (GlobalMotion.Input_CardEx2[(int)e_input_extCard2.上输送治具检测2] && GlobalVar.Laser_pros != null && GlobalVar.Laser_pros.Count > 1)
                        {
                            try
                            {
                                var arr = GlobalVar.Laser_pros.Take(2).ToArray();//防止中途被clear()
                                if (arr.Length > 1)
                                {
                                    lbl_cutRFID1.Text = arr[0].ProId;
                                    lbl_cutRFID2.Text = arr[1].ProId;
                                }
                                else
                                {
                                    lbl_cutRFID1.Text = "";
                                    lbl_cutRFID2.Text = "";
                                }
                            }
                            catch { }
                        }
                        else
                        {
                            lbl_cutRFID1.Text = "";
                            lbl_cutRFID2.Text = "";
                        }
                        if (GlobalMotion.Input_CardEx2[(int)e_input_extCard2.上输送治具检测3]&&GlobalVar.Label_pros!=null && GlobalVar.Label_pros.Count>1)
                        {
                            try
                            {
                                var arr = GlobalVar.Label_pros.Take(2).ToArray();//防止中途被clear()
                                if (arr.Length > 1)
                                {
                                    lbl_labelRFID1.Text = arr[0].ProId;
                                    lbl_labelRFID2.Text = arr[1].ProId;
                                }else
                                {
                                    lbl_labelRFID1.Text = "";
                                    lbl_labelRFID2.Text = "";
                                }
                            }
                            catch { }
                        }
                        else
                        {
                            lbl_labelRFID1.Text = "";
                            lbl_labelRFID2.Text = "";
                        }
                        #endregion

                        #region 右边
                        lbl_flowCut.Text = GlobalMotion.e_Cut.ToString();
                        lbl_flowLabel.Text = GlobalMotion.e_LabelingFlow.ToString();
                        lbl_flowFront.Text = GlobalMotion.e_ConveryFront.ToString();
                        lbl_flowSecord.Text = GlobalMotion.e_ConveryLaser.ToString();
                        lbl_flowThird.Text = GlobalMotion.e_ConveryLabel.ToString();
                        lbl_fly1.Text = GlobalMotion.fly1.ToString();
                        lbl_fly2.Text = GlobalMotion.fly2.ToString();
                        lbl_down.Text = GlobalMotion.e_Down.ToString();
                        lbl_OK.Text = GlobalVar.closeSave.OKCount.ToString();
                        lbl_All.Text = (GlobalVar.closeSave.NGCount + GlobalVar.closeSave.OKCount).ToString();
                        lbl_runtime.Text = GlobalVar.closeSave.runTime_today.ToString("HH:mm:ss");
                        lbl_stoptime.Text = GlobalVar.closeSave.stopTime_today.ToString("HH:mm:ss");
                        lbl_estoptime.Text = GlobalVar.closeSave.EstopTime_today.ToString("HH:mm:ss");
                        lbl_CT.Text = ((decimal)GlobalVar.sw_CT.ElapsedMilliseconds / (decimal)1000.0).ToString("F02");
                        switch (MotionControl.GlobalVariable.OperLevel)
                        {
                            case (int) MotionControl.operLevel.technician:
                                btn_log.Text = "工艺员";
                               break;
                            case (int)MotionControl.operLevel.admin:
                                btn_log.Text = "工程师";
                                break;
                            case (int)MotionControl.operLevel.operatorStaff:
                                btn_log.Text = "操作员";
                                break;
                            case (int)MotionControl.operLevel.superAdmin:
                                btn_log.Text = "管理员";
                                break;
                        }
                       if(!string.IsNullOrEmpty(GlobalVar.closeSave.CurrentTypeName)&& GlobalVar.closeSave.CurrentTypeName.Contains(GlobalVar.char_VersionSpilt))
                        {
                            var arrType = GlobalVar.closeSave.CurrentTypeName.Split(GlobalVar.char_VersionSpilt);
                            tbx_typeName.Text = arrType[0];
                          
                            if (GlobalVar.tv_list != null && GlobalVar.tv_list.Count > 0)
                            {
                               var curType= GlobalVar.tv_list.Where(a => a.type == arrType[0] && a.Version == arrType[1]).FirstOrDefault();
                                if (curType != null)
                                {
                                    var curConfig = curType.GetConfig();
                                    lbl_config.Text = curConfig;
                                    if (string.IsNullOrEmpty(curConfig))
                                        tbx_Version.Text = curType.Version;
                                    else
                                        tbx_Version.Text = curType.Version.Replace(curConfig, "");
                                }
                            }
                        }
                        if ((GlobalVar.closeSave.runTime_today.Millisecond + GlobalVar.closeSave.stopTime_today.Millisecond) > 0)
                        {
                            var runTime = (GlobalVar.closeSave.runTime_today - DateTime.Now.Date).TotalMilliseconds;
                            var stopTime = (GlobalVar.closeSave.stopTime_today - DateTime.Now.Date).TotalMilliseconds;
                            var EstopTime = (GlobalVar.closeSave.EstopTime_today - DateTime.Now.Date).TotalMilliseconds;
                            var rate = (double)(stopTime + runTime) / (stopTime + runTime+ EstopTime);
                            chartCircle1.UpdateOkRate(rate * 100);
                            lbl_runTimeRate.Text =( rate * 100).ToString("F02");
                        }
                        #endregion
                    }));
                }
            }catch(Exception ex)
            {

            }
        }
      
        private void btn_Pause_Click(object sender, EventArgs e)
        {
            GlobalVar.isPause =true;
            GlobalVar.curStatus = e_Status.暂停中;
        }
        private bool IsOpenReset = false;
        private void btn_Start_Click(object sender, EventArgs e)
        {
            displalyInfo.displayInfoMain(((Button)sender).Text + "按下");
           // lst_Button.ForEach(a=>{
              //  if (a.Name == ((Button)sender).Name)
             //       a.BackColor = selectcolor;
            //    else
             //       a.BackColor = backcolor;
           // });
            if (!GlobalVar.isAutoRun)
            {
                if (!IsOpenReset)
                {
             
                    string str = "开机请先复位";
                    displalyInfo.displayErrorMain(str);
                    MessageBox.Show(str);
                    return;
                }
                if (!GlobalVar.isAllHome && !GlobalVar.IsManThrought)
                {
                    string str = "请先回原";
                    displalyInfo.displayErrorMain(str);
                    MessageBox.Show(str);
                    return;
                }
                if(GlobalVar.cameraList!=null&&GlobalVar.cameraList.Count>0)
                {
                    var arr=GlobalVar.cameraList.Where(a => !a.isInitSuccess).ToArray();
                    if(arr.Length>0)
                    {
                        string str = "相机未连接  请重启软件";
                        displalyInfo.displayErrorMain(str);
                        MessageBox.Show(str);
                    }
                }
                if (GlobalVar.IsManThrought)
                {
                    if (GlobalVar.IsThrought)
                    {
                        GlobalVar.curWorkMode = e_WorkMode.过站模式;
                        cmb_workMode.SelectedItem = e_WorkMode.过站模式.ToString();
                    }
                    else
                    {
                        GlobalVar.curWorkMode = e_WorkMode.人工过站模式;
                        cmb_workMode.SelectedItem = e_WorkMode.人工过站模式.ToString();
                    }
                }
                else
                {
                    GlobalVar.curWorkMode = e_WorkMode.生产模式;
                    cmb_workMode.SelectedItem = e_WorkMode.生产模式.ToString();
                }
                if (IsFirstStart)
                {

                    GlobalMotion.nLabelTimes = 0;
                    GlobalVar.curStatus = e_Status.未知;
                    IsFirstStart = false;
                    GlobalVar.isFlying1OK = true;
                    GlobalVar.isFlying2OK = true;
                    GlobalMotion.Step_ConveryUp(e_Step_ConveryUp.入料段治具阻挡, e_MachineStatus.无控制);
                    GlobalMotion.Step_ConveryUp(e_Step_ConveryUp.一段治具阻挡, e_MachineStatus.无控制);
                    GlobalMotion.Step_ConveryUp(e_Step_ConveryUp.二段治具阻挡, e_MachineStatus.无控制);
                    GlobalMotion.ConveryControrl(e_ConveryControl.上层输送启动, e_MachineStatus.无控制);
                    Thread.Sleep(GlobalVar.userConfig.ConveryOpen_time);
                    GlobalMotion.e_ConveryFront = e_Flow_ConveryUp.等待入料治具到位;
                    GlobalMotion.e_ConveryLabel = e_Flow_ConveryUp.等待二段治具到位;
                    GlobalMotion.e_ConveryLaser = e_Flow_ConveryUp.等待一段治具到位;
                    GlobalMotion.e_ConveryOver = e_Flow_ConveryUp.等待一段治具到位;
                    GlobalMotion.e_ConveryMan = e_Flow_ConveryUp.等待人工站到达;
           
                    GlobalMotion.e_Cut = e_Flow_Cut.等待有工装到达;
                    GlobalMotion.e_LabelingFlow = e_Flow_Labeling.取标签;
                    GlobalVar.IsStart_EndWork = false;
                    GlobalVar.IsEndWork = false;
                    GlobalVar.IsProccessed1 = false;
                    GlobalVar.IsProccessed2 = false;
                    GlobalVar.Label_Start = false;
                    GlobalVar.LabelFinshed = false;
                    GlobalVar.Cut_Finish = true;
                    GlobalVar.Cut_Start = false;
                    GlobalVar.ScanFinished = false;
                    GlobalVar.e_Camera_Pos1 = e_Camera_Pos.未拍照;
                    GlobalVar.e_Camera_Pos2 = e_Camera_Pos.未拍照;
                    GlobalVar.e_Camera_Check1 = e_Camera_Pos.未拍照;
                    GlobalVar.e_Camera_Check2 = e_Camera_Pos.未拍照;
                    GlobalVar.IsPosBeforeLabel = false;
                    GlobalVar.front_pros = new List<ProductInfo>();
                    GlobalVar.Laser_pros = new List<ProductInfo>();
                    GlobalVar.Label_pros = new List<ProductInfo>();
                    displalyInfo.displayInfoMain("回零后首次开机");
                }
                this.Invoke(new Action(() => {
                    btn_Home.Enabled = false;
                    btn_FinishWork.Enabled = true;
                  
                }));
                GlobalVar.IsEndWork = false;
                GlobalVar.isAutoRun = true;
                GlobalVar.isPause = false;//要在isAutoRun后
                Task.Run(() =>
                {
                    Thread.Sleep(100);
                    GlobalMotion.Task_StartCheck();
                });
            }
            else
            {
                if (GlobalVar.isPause)
                {
                    //GlobalVar.curStatus = e_Status.未知;
                    GlobalVar.isPause = false;

                }
                else
                {
                    //GlobalVar.isPause = true;
                    //GlobalVar.curStatus = e_Status.暂停中;

                }

            }
            GlobalVar.IsMesEstop = false;
        }
        bool isAirAll = true;
        bool IsFirstStart = true;
        private Color backcolor = Color.Gray;
        private Color selectcolor = Color.SteelBlue;
        private void btn_Home_Click(object sender, EventArgs e)
        {
            lst_Button.ForEach(a => {
                    a.BackColor = selectcolor;
            });
            if (GlobalVar.isEstop)
            {
                GlobalMotion.MachineState(e_MachineStatus.异常急停, "急停中不能复位");
                return;
            }

            isAirAll = true;
            var forms = Application.OpenForms;
            foreach (var curForm in forms)
            {
                if (((Form)curForm).Name == "FormAlarm" || ((Form)curForm).Name == "FormDeviceError")
                {
                    ((Form)curForm).WindowState = FormWindowState.Minimized;
                }
            }

            if (!GlobalVar.isPause && GlobalVar.isAutoRun)
            {
                MessageBox.Show("先停止自动运行再复位！");
                return;
            }

            if (!GlobalVar.IsTcpReset)
            {
                if (MessageBox.Show("所有轴将进行回零,确认要复位吗？", "询问", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
                {
                    btn_Home.Enabled = true;
                    return;
                }
            }

            if (GlobalVar.isReseting)
            {
                MessageBox.Show("已在复位中  操作无效");
                return;
            }

            btn_Start.Enabled = false;
            GlobalVar.IsStart_EndWork = false;
            GlobalVar.IsEndWork = false;
            GlobalVar.IsTcpReset = false;
            GlobalVar.isReseting = true;
            GlobalVar.isPause = false;
            
            IsOpenReset = true;
            GlobalVar.isAutoRun = false;
            Thread.Sleep(100);
            IsFirstStart = true;
            GlobalVar.IsMesEstop = false;
            btn_Home.Enabled = false;

            //开始复位
            var nres = GlobalMotion.home_all_continue();
            GlobalVar.isReseting = false;
            btn_Home.Enabled = true;
            if (nres == 1)
            {
                GlobalVar.curStatus = e_Status.设备复位完成;
                displalyInfo.displayInfoMain("所有轴回零完成！");
                MessageBox.Show("所有轴回零完成！");
            }
            else
            {
                GlobalVar.curStatus = e_Status.设备未复位;
                GlobalVar.isEstop = true;////临时
                GlobalMotion.MachineState(e_MachineStatus.异常急停, "所有轴回零失败!");
             
            }
            btn_Start.Enabled = true;
            
        }
      
        private int btn_HomeProccess(string reset)
        {
            
            this.Invoke(new Action(() =>
            {
                btn_Home_Click(btn_Home, null);
            }));
            return 1;
        }
        private int btn_StartProccess(string reset)
        {
            this.Invoke(new Action(() =>
            {
                btn_Start_Click(btn_Start, null);
            }));
            return 1;
        }
        private int btn_EstopProccess(string stop)
        {
          
            if (GlobalVar.isEstop|| stop == "急停取消")
            {
              
                {
                    GlobalVar.isEstop = false;
                    this.Invoke(new Action(() =>
                    {
                        btn_Home.Enabled = true;
                    }));
                    displalyInfo.displayInfoMain("急停取消");
                }
            }
            else
            {
                MotionControl.GlobalVariable.HOperation.AllAxisStop(GlobalMotion.Card_1.m_CardID);
                this.Invoke(new Action(() =>
                {
                    btn_Start.Enabled = true;
                }));
                GlobalVar.errorTips[(int)e_errorType.softEstop].haveInfo = true;
                GlobalVar.isEstop = true;
                GlobalVar.isAutoRun = false;
                GlobalVar.isAllHome = false;
                GlobalVar.isPause = true;
             
                GlobalMotion.MachineState(e_MachineStatus.异常急停, "触发软急停");
                this.Invoke(new Action(() => {
                    this.Enabled = true;
                }));
                GlobalVar.IsMesEstop = false;
                displalyInfo.displayInfoMain("软件急停");
            }
            if (!IsOpenReset)
            {
                if (GlobalVar.isEstop)
                    GlobalVar.curStatus = e_Status.停止中;
                else
                {
                    if (GlobalVar.curStatus == e_Status.停止中)
                        GlobalVar.curStatus = e_Status.未知;
                }
            }
            else
            {
                if (GlobalVar.isEstop)
                    GlobalVar.curStatus = e_Status.停止中;
                else
                {
                    if (GlobalVar.curStatus == e_Status.停止中)
                        GlobalVar.curStatus = e_Status.未知;
                }
            }
            GlobalVar.IsMesEstop = false;
            return 1;
        }
        private void PageMain_FormClosing(object sender, FormClosingEventArgs e)
        {
          
        }

        private void btn_FinishWork_Click(object sender, EventArgs e)
        {
            displalyInfo.displayInfoMain(((Button)sender).Text + "按下");
            //lst_Button.ForEach(a => {
            //    if (a.Name == ((Button)sender).Name)
            //        a.BackColor = selectcolor;
            //    else
            //        a.BackColor = backcolor;
            //});
            if (GlobalVar.isAutoRun)
            {
                GlobalVar.IsEndWork = true;
            }
            else
            {
                MessageBox.Show("当前未处于自动运行中  操作无效!");
            }
           
        }

        private void btn_estop_Click(object sender, EventArgs e)
        {
            GlobalVar.btn_Estop(btn_estop.Text);
          
        }

        private void btn_ChangeStatus_Click(object sender, EventArgs e)
        {
            if(GlobalVar.isAutoRun)
            {
                if (GlobalVar.isPause)
                {
                    // GlobalVar.isPause = false;
                    //   GlobalVar.curStatus = e_Status.未知;
                    GlobalVar.IsStatusAuto = !GlobalVar.IsStatusAuto;
                }
                else
                {
                   // GlobalVar.isPause = true;
                 //   GlobalVar.curStatus = e_Status.暂停中;
                    
                }
            }else
            {
                MessageBox.Show("机器处于未启动状态,操作无效");
            }
           
        }

        private void btn_log_Click(object sender, EventArgs e)
        {
            var logPage = new PageLogin();
            logPage.ShowDialog();
        }

        private void cmb_workMode_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmb_workMode.SelectedIndex > -1)
            {
                var curMode = "生产模式";
                try
                {
                    curMode = cmb_workMode.SelectedItem.ToString();
                }
                catch
                {

                }
                switch (curMode)
                {
                    case "生产模式":
                        GlobalVar.IsThrought = false;
                        GlobalVar.IsManThrought = false;
                        GlobalVar.curWorkMode = e_WorkMode.生产模式;
                        break;
                    case "过站模式":
                        GlobalVar.IsManThrought = true;
                        GlobalVar.IsThrought = true;
                        GlobalVar.curWorkMode = e_WorkMode.过站模式;
                        break;
                    case "人工过站模式":
                        GlobalVar.IsManThrought = true;
                        GlobalVar.IsThrought = false;
                        GlobalVar.curWorkMode = e_WorkMode.人工过站模式;
                        break;
                }
                lbl_cutRFID1.Focus();
            }
        }

        private void tableLayoutPanel4_Paint(object sender, PaintEventArgs e)
        {

        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            CMachine.Instance.IsTestModel = ckb_IsOldTest.Checked;
        }



        public static bool IsOpen { get; set; }
        private static Control control;
        private static Process visionProcess;
        /// <summary>
        /// 打开视觉窗体
        /// </summary>
        /// <param name="exePath">打开视觉程序的路径</param>
        public static void OpenVisionWindow(out bool result, int timeOut = 60_000)
        {
            string path = @"F:\文字版站视觉程序\广州维高P4站视觉4.0-1124\维高P4-4.4-新.sol";// ProductParameterService.Instance.ProductParam.CurrentProductType.VisionPath;
            result = false;
            if (!File.Exists(path))
            {
                GlobalMotion.TipInfo($"嵌入视觉程序失败,路径下找不到视觉程序:{path}");
                result = false;
                return;
            }

            control.BeginInvoke(new Action(async () =>
            {
                try
                {
                    //获取当前进程中是否有视觉软件
                    visionProcess = Process.GetProcessesByName("VisionMaster").FirstOrDefault();

                    if (visionProcess == null || visionProcess.HasExited)
                    {
                        // 启动外部应用程序
                        Run_exe(path);
                        
                        //visionProcess = Process.Start(path);
                    }

                    //每隔1秒检测一下视觉是否连接上，连接上了则代表视觉已经准备好
                    //int receiveCount = 0;
                    //bool isLink = false;
                    //bool isReceive = false;
                    //DateTime endTime = DateTime.Now.AddMilliseconds(timeOut);
                    //while (DateTime.Now < endTime)
                    //{
                    //    isLink = client.Open();

                    //    if (isLink)
                    //    {
                    //        client.SendAndReceive("T1,0", out string receiveMsg, 1_000);

                    //        if (!receiveMsg.IsNullOrWhiteSpace())
                    //        {
                    //            receiveCount++;
                    //        }

                    //        if (receiveCount > whileTimes)
                    //        {
                    //            isReceive = true;
                    //            await Task.Delay(2_000);
                    //            break;
                    //        }
                    //    }

                    //    await Task.Delay(500);
                    //}



                    //等待程序窗口创建完毕
                    int whileTimes = 5;
                    await Task.Delay(5000);
                    visionProcess = Process.GetProcessesByName("VisionMaster").FirstOrDefault();
                    visionProcess.WaitForInputIdle();

                    if (visionProcess == null || visionProcess.MainWindowHandle == IntPtr.Zero)
                    {
                        GlobalMotion.TipInfo($"嵌入视觉程序失败,无法启动程序:{path}");
                        // result = false;
                        return;
                    }

                    bool rlt = false;
                    for (int i = 0; i < whileTimes; i++)
                    {
                        visionProcess.WaitForInputIdle();

                        // 获取程序的主窗口句柄
                        IntPtr appWin = visionProcess.MainWindowHandle;

                        // 设置为子窗口
                        var a = WindowHelp.SetParent(appWin, control.Handle);

                        if (a.Equals(0x0000000000000000))
                        {
                            visionProcess = Process.GetProcessesByName("VisionMaster").FirstOrDefault();
                        }

                        await Task.Delay(1_000);

                        // 将窗口移动到Panel控件内
                        //WindowHelp.ShowWindow(appWin,(int)ProcessWindowStyle.Maximized);
                        rlt = WindowHelp.MoveWindow(appWin, 0, 0, control.Width, control.Height, true);

                        if (rlt)
                        {
                            break;
                        }
                    }

                    if (!rlt)
                    {
                        GlobalMotion.TipInfo($"嵌入视觉程序失败: 视觉程序嵌入不到主程序窗口中");
                    }
                    // result = true;
                    IsOpen = rlt;
                }
                catch (Exception ex)
                {
                    GlobalMotion.TipInfo($"嵌入视觉程序失败: {ex.Message}");
                }

            }));
            result = IsOpen;
        }

        /// <summary>
        /// 关闭视觉窗体
        /// </summary>
        public static async void CloseVisionWindow()
        {
            try
            {
                if (visionProcess != null)
                {
                    visionProcess.Kill();

                    await Task.Delay(1000);

                    visionProcess = null;

                    IsOpen = false;
                }
            }
            catch (Exception)
            {
            }
        }

        public static bool Run_exe(string exePath)
        {
            bool isExist = false;
            try
            {
                visionProcess = new Process();
                visionProcess.StartInfo.FileName = exePath;
                visionProcess.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
                visionProcess.Start();

                //判断程序是否在运行
                DateTime endTime = DateTime.Now.AddMilliseconds(5);
                while (DateTime.Now < endTime)
                {
                    visionProcess.WaitForExit(3000);
                    if (visionProcess.HasExited == false)
                    {
                        isExist = true;
                        break;
                    }
                    
                    //else
                    //{
                    //    isExist = false;
                    //    break;
                    //}
                }
            }
            catch
            {
                return isExist;
            }
            return isExist;

        }

    }
    public enum e_WorkMode
    {
        生产模式,
        过站模式,
        人工过站模式
    }
}
